﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Update.Utility;

namespace Update
{
	public partial class MainForm : Form
	{
		private String localPath;
		private String ftpPath;
		private FtpDownloader ftpDownloader;
		public MainForm(String[] args)
		{
			InitializeComponent();
			Init();

			localPath = args[0];
			ftpPath = args[1];
		}

		private void Init()
		{
			this.StartPosition = FormStartPosition.CenterScreen;
			this.FormBorderStyle = FormBorderStyle.FixedSingle;
			this.MaximizeBox = false;
			this.Shown += Form_Shown;

			btnCancel.Click += btnCancel_Click;
			bgUpdateWorker.DoWork += bgUpdateWorker_DoWork;
			bgUpdateWorker.RunWorkerCompleted += bgUpdateWorker_RunWorkerCompleted;

			ftpDownloader = new FtpDownloader();
			ftpDownloader.DownloadEvent += DownloadEventHandler;
		}

		private void Form_Shown(Object sender, EventArgs e)
		{
			bgUpdateWorker.RunWorkerAsync();
		}

		private delegate void SetPgBarValueCallBack(int value);
		private void SetPgBarValue(int value)
		{
			if (pgBar.InvokeRequired)
			{
				SetPgBarValueCallBack d = new SetPgBarValueCallBack(SetPgBarValue);
				pgBar.Invoke(d, value);
			}
			else
			{
				pgBar.Value = value;
			}
		}

		private void DownloadEventHandler(Object sender, FtpDownloader.DownloadEventArgs e)
		{
			SetPgBarValue(e.FinishedPercent);
		}

		private void btnCancel_Click(Object sender, EventArgs e)
		{

		}

		private void bgUpdateWorker_DoWork(Object sender, DoWorkEventArgs e)
		{
			ftpDownloader.Download(ftpPath, localPath);
		}

		private void bgUpdateWorker_RunWorkerCompleted(Object sender, RunWorkerCompletedEventArgs e)
		{
			SetPgBarValue(100);
			try
			{
				System.Diagnostics.Process.Start(localPath);
			}
			catch (System.Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
			this.Dispose();
		}
	}
}
